package com.leyou.geteway.filters;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.RsaUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.geteway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthFilter extends ZuulFilter {
    @Autowired
    private JwtProperties prop;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//过滤器类型，前置过滤器
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;//过滤器顺序
    }

    @Override//是否过滤
    public boolean shouldFilter() {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = ctx.getRequest();
        //获取请求的url请求
        String path = request.getRequestURI();

        //判断是否放行
        return !isAllowPath(path);
    }

    private boolean isAllowPath(String path) {
        List<String> allowPaths = new ArrayList<>();
        allowPaths.add("/api/auth");
        allowPaths.add("/api/search");
        allowPaths.add("/api/user/register");
        allowPaths.add("/api/user/check");
        allowPaths.add("/api/user/code");
        allowPaths.add("/api/item");
        //遍历白名单
        for (String allowPath : allowPaths) {
            //判断是否允许
            if (path.startsWith(allowPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = ctx.getRequest();
        //获取cookie中的token

        String token = CookieUtils.getCookieValue(request, prop.getCookieName());//"LY_TOKEN"
        //解析token
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, RsaUtils.getPublicKey(prop.getPubKeyPath()));//"F:\\2019Java\\upload\\rsa.pri"
            //TODO 校验权限
        } catch (Exception e) {
            //解析token失败，未登录，拦截
            ctx.setSendZuulResponse(false);
            //返回状态码
            ctx.setResponseStatusCode(403);

        }
        //校验权限
        return null;
    }
}
